package com.atguigu.ggkt.vod.service.impl;


import com.alibaba.excel.EasyExcel;
import com.atguigu.ggkt.exception.GgktException;
import com.atguigu.ggkt.vo.vod.SubjectEeVo;
import com.atguigu.ggkt.vod.mapper.SubjectMapper;
import com.atguigu.ggkt.model.vod.Subject;
import com.atguigu.ggkt.vod.listener.SubjectListener;
import com.atguigu.ggkt.vod.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author sleephardzz
 * @since 2023-07-09
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    //已注入为Component，因此可以取到
    @Autowired
    private SubjectListener subjectListener;

    //课程分类列表
    //懒加载，每次查一层
    @Override
    public List<Subject> selectSubjectList(Long id) {
        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Subject::getParentId, id);
        List<Subject> subjectList = baseMapper.selectList(wrapper);
        //已完善：箭头隐藏
        /** 对象进一步封装，如果有下层，将hasChild置为true */
        for (Subject subject : subjectList) {
            Long sId = subject.getId();
            /**
             * 不能这样写：
             boolean hasChild = subject.isChild(sId);
             否则就会在subject中创建方法，
             使用this，将创建在这
             */
            boolean hasChild = this.isChild(sId);
            subject.setHasChildren(hasChild);
        }
        return subjectList;
    }

    //课程分类导出
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //符合easyexcel的上下文
            response.setContentType("application/vnd.ms-excel");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("课程分类", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //查询课程分类表所有数据：
            List<Subject> subjectList = baseMapper.selectList(null);

            //TODO List<Subject> 变为 List<SubjectEeVo>
            List<SubjectEeVo> sVoList = new ArrayList<>();
            subjectList.forEach(s -> {
                SubjectEeVo sVo = new SubjectEeVo();
                BeanUtils.copyProperties(s, sVo);
                sVoList.add(sVo);
            });

            //写：
            EasyExcel.write(response.getOutputStream(), SubjectEeVo.class)
                    .sheet("课程分类")
                    .doWrite(sVoList);
        } catch (Exception e) {
            throw new GgktException(20001, "导出失败");
        }
    }

    //    课程导入
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectEeVo.class,
                    subjectListener)
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            throw new GgktException(20001,"导入失败");
        }
    }

    //是否有下一层
    private boolean isChild(Long sId) {
        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Subject::getParentId, sId);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0 ? true : false;
    }
}
